import SDK from '../utils/SDK';
import { getTemplateConfig } from '../config/template';
import { getConfig, needBleAbility } from '../config/product';

import ServiceInfoManager from '../utils/ServiceInfoManager';
import SecureStore from '../utils/AsyncStorage';
import { reportStopConfigWifiEvent, reportStartConfigWifiEvent } from './aggregateData';
import configWifiModel from '../pages/configDevice/models/configWifi';

const config = getTemplateConfig();
const gizwitsConfig = config.gizwits;

export async function init({ cloudServiceInfo }: { cloudServiceInfo: IServiceInfo }) {
  if (!cloudServiceInfo) {
    // eslint-disable-next-line no-param-reassign
    cloudServiceInfo = await ServiceInfoManager.getServiceInfo();
  }

  const productInfo = getConfig().filter(i => !!i.productKey);
  const needBle = needBleAbility();
  console.log('蓝牙能力', needBle);

  const appID = gizwitsConfig.wxAppID;
  const appSecret = gizwitsConfig.wxAppSecret;
  const token = await SecureStore.getItem('token');
  const uid = await SecureStore.getItem('uid');
  // console.log('productInfo', productInfo);
  return SDK.init({
    appID,
    appSecret,
    productInfo,
    cloudServiceInfo,
    token,
    uid,
    needInitBle: needBle,
  });
}

export async function getDeviceList() {
  const token = await SecureStore.getItem('token');
  if (token) {
    return SDK.getBoundDevices();
  }
  return { success: false, error: 'token不存在' };
}

// 发送数据点给设备
export async function write({ device, data, sn = 0 }: { device: IDevice; data: any; sn?: number }) {
  return SDK.write(device, data);
}

// 发送广播数据
export async function writeBigData({ device, data }: { device: IDevice; data: number[] }) {
  return SDK.writeBigData(device, data);
}

export async function setDeviceOnboardingDeploy({
  ssid,
  key,
  mode,
  timeout,
  gagentTypes,
  softAPSSIDPrefix,
  isBind = true,
}: any) {
  const deployParams = {
    ssid,
    password: key,
    mode,
    timeout,
    softAPSSIDPrefix,
    isBind,
    gagentTypes,
  };

  // 开始配网前进行监控
  reportStartConfigWifiEvent(deployParams);
  const sdkResPromise = SDK.setDeviceOnboardingDeploy(deployParams);
  sdkResPromise.then(sdkRes => {
    if (sdkRes.success) {
      configWifiModel.sdkResCache = sdkRes;
    } else {
      reportStopConfigWifiEvent({
        devices: [],
        sdkRes,
        saasRes: {},
        paasRes: {},
      });
    }
  });

  return sdkResPromise;
}

export async function stopDeviceOnboarding() {
  return SDK.stopDeviceOnboardingDeploy();
}

export async function setSubscribe({ device, productSecret, subscribed }: ISubscribeParam) {
  return SDK.setSubscribe({ device, subscribed });
}
